package com.caow.composebase

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.caow.composebase.widget.LoadingDialog
import java.lang.reflect.ParameterizedType

/**
 * @Author caow
 * 2023/6/30
 */
abstract class BaseFragment<VM : BaseViewModel> : Fragment() {


    protected val TAG by lazy { javaClass.simpleName }

    protected val viewModel: VM by lazy {
        val entityClass: Class<VM> =
            (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>

        val constructor = entityClass.getConstructor()
        constructor.newInstance()

    }

    abstract fun initLayoutId(): Int
    abstract fun initViewModelId(): Int

    // 加载中弹窗
    private val loadingDialog by lazy { LoadingDialog(requireActivity()) }

//    override fun onCreateView(
//        inflater: LayoutInflater,
//        container: ViewGroup?,
//        savedInstanceState: Bundle?
//    ): View? {
////        val view = inflater
////            .inflate(initLayoutId(), container, false)
////        Log.i("caow", "view ====== $view")
//        binding = DataBindingUtil.inflate(inflater, initLayoutId(), container, false)
//        return binding.root
//    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        binding.setVariable(initViewModelId(), viewModel)
        lifecycle.addObserver(viewModel)
        initLoadingDialog()
    }

    private fun initLoadingDialog() {
        viewModel.showLoadingDialog.observe(viewLifecycleOwner, Observer { loadingDialog.show() })
        viewModel.dismissLoadingDialog.observe(viewLifecycleOwner, Observer { loadingDialog.dismiss() })
    }
}